package com.nick.proxy.custom;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by xiaobao on 2017/7/9.
 */
public class CustomClassLoader extends ClassLoader {
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            FileInputStream classFile = null;
            try {
                classFile = new FileInputStream("$Proxy0.class");
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = classFile.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                return  defineClass(CustomClassLoader.class.getPackage().getName().replace("/", ".") + "." + name, out.toByteArray(), 0, out.size());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                    classFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        return null;
    }
}
